package com.gonsin.i18n.logic.controller;

import com.gonsin.i18n.logic.T;
import com.gonsin.i18n.logic.config.I18nConfig;
import com.gonsin.i18n.logic.machine.Languages;
import com.gonsin.i18n.logic.models.KeywordModel;
import com.gonsin.i18n.logic.utils.AESUtils;
import com.google.gson.Gson;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/api/i18n")
public class I18nController {

    @PostMapping("/{project}/{lang}")
    public String getKeywords(
            @PathVariable("project") String project, @PathVariable("lang") String lang){
        Map<String, Object> result = new HashMap<>();
        result.put("state", 200);
        result.put("message", "");
        result.put("data", T.allKeywords(project, lang));
        I18nConfig config = T.config();
        String json = new Gson().toJson(result);
        return AESUtils.encryptECB(json, config.getKey(), config.getEncoder());
    }

    @GetMapping("/langs")
    public String getAllLangs(){
        Map<String, Object> result = new HashMap<>();
        result.put("state", 200);
        result.put("message", "");
        result.put("data", Languages.list());
        String json = new Gson().toJson(result);
        return json;
    }

    @PostMapping("/{project}")
    public String getLangs(@PathVariable("project") String project){
        Map<String, Object> result = new HashMap<>();
        result.put("state", 200);
        result.put("message", "");
        result.put("data", T.allLang(project));
        I18nConfig config = T.config();
        String json = new Gson().toJson(result);
        return AESUtils.encryptECB(json, config.getKey(), config.getEncoder());
    }

    /**
     * 上传新的未设置的字符串
     */
    @PutMapping("/{project}/{lang}")
    public String putNewKeyword(
            @PathVariable("project") String project, @PathVariable("lang") String lang,
            @RequestParam("keyword") String keyword, @RequestParam(required = false, name = "common") String common){
        I18nConfig config = T.config();
        keyword = AESUtils.decryptECB(keyword, config.getKey(), config.getEncoder());
        List<KeywordModel> langs = T.allLang(project);
        for(KeywordModel l : langs){
            T.insertNewKeyword(project, l.getLang(), keyword, keyword, true, common);
        }
        Map<String, Object> result = new HashMap<>();
        result.put("state", 200);
        result.put("message", "");
        String json = new Gson().toJson(result);
        return AESUtils.encryptECB(json, config.getKey(), config.getEncoder());
    }

}
